const User = require('../model/user');
const { sign,verify,decode} = require('../util/jwt')
const resolvers = {
    Query: {
        async users() {
            //查询数据库返回数据
            const res = await User.find();
            return res
        },
       async currentUser(parent, { user }, {token}) {
           await verify(token,'erty23456u')
            return {
                username: '1',
                password: '2',
                email: '3',
                token
            }
        }

    },
    Mutation: {
        async login(parent, { user }, context) {
            const loginUser = await User.findOne({
                password: user.password,
                email: user.email,
            })
            if (!loginUser) {
                throw new Error('用户名或密码错误')
            }
            return loginUser;
        },
        async createUser(parent, { user }, context) {
            //判断用户名是否存在
            const username = await User.findOne({ username: user.username })
            //判断邮箱是否存在
            const email = await User.findOne({ email: user.email })
            if (username || email) {
                throw new Error('用户名或密码已存在')
            }
            const dbUser = new User(user);
            const result = await dbUser.save()
            const token = await sign({
                userId: result._id
            }, 'erty23456u', {
                expiresIn: 60 * 60 * 24
            })
            result.token = token;
            return result
        }
    }
}
module.exports = resolvers;